package com.HQCourse.order.order.service.impl;


import com.HQCourse.Exception.HQCourseException;
import com.HQCourse.client.course.CourseClient;
import com.HQCourse.clilent.userchilent.UserInfoFeignClient;
import com.HQCourse.example.activity.CouponInfoFeignClient;
import com.HQCourse.order.order.mapper.OrderInfoMapper;
import com.HQCourse.order.order.service.OrderDetailService;
import com.HQCourse.order.order.service.OrderInfoService;
import com.HQCourse.utils.AuthContextHolder;
import com.HQCourse.utils.OrderNoUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.HQCourse.model.activity.CouponInfo;
import com.example.HQCourse.model.order.OrderDetail;
import com.example.HQCourse.model.order.OrderInfo;
import com.example.HQCourse.model.user.UserInfo;
import com.example.HQCourse.model.vod.Course;
import com.example.HQCourse.vo.order.OrderFormVo;
import com.example.HQCourse.vo.order.OrderInfoQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单表 订单表 服务实现类
 * </p>
 *
 * @author zww
 * @since 2023-07-02
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserInfoFeignClient userInfoFeignClient;
    @Autowired
    private CouponInfoFeignClient couponInfoFeignClient;
    @Autowired
    private CourseClient client;

    @Override
    public Long submitOrder(OrderFormVo orderFormVo) {
        //获取生成订单id
        Long couponId = orderFormVo.getCouponId();
        Long courseId = orderFormVo.getCourseId();
        Long couponUseId = orderFormVo.getCouponUseId();
//        Long courseId = orderFormVo.getCourseId();

        //获取当前用户的id
        Long userId = AuthContextHolder.getUserId();
        //判断当前用户
        //查询当前用户是否已有当前课程的订单
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getCourseId, courseId);
        queryWrapper.eq(OrderDetail::getUserId, userId);
        OrderDetail orderDetailExist = orderDetailService.getOne(queryWrapper);
        if(orderDetailExist != null){
            return orderDetailExist.getId(); //如果订单已存在，则直接返回订单id
        }
        Course course = client.getById(courseId);
        if(course==null){
            throw new HQCourseException(20001,"课程不存在");
        }
        UserInfo userInfo = userInfoFeignClient.getById(userId);
        if(userInfo==null){
            throw new HQCourseException(20001,"用户不存在");
        }
        //优惠卷金额
        BigDecimal couponReduce = new BigDecimal(0);
        //根据优惠卷id查询优惠卷信息
        if(couponId==null){
            CouponInfo couponInfo = couponInfoFeignClient.getById(couponId);
            BigDecimal amount = couponInfo.getAmount();
        }

        //创建订单
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userInfo.getNickName());
        orderInfo.setPhone(userInfo.getPhone());
        orderInfo.setProvince(userInfo.getProvince());
        orderInfo.setOriginAmount(course.getPrice());
        orderInfo.setCouponReduce(couponReduce);
        orderInfo.setFinalAmount(orderInfo.getOriginAmount().subtract(orderInfo.getCouponReduce()));
        orderInfo.setOutTradeNo(OrderNoUtils.getOrderNo());
        orderInfo.setTradeBody(course.getTitle());
        orderInfo.setOrderStatus("0");
        this.save(orderInfo);
        //生成订单接口
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(orderInfo.getId());
        orderDetail.setUserId(userId);
        orderDetail.setCourseId(courseId);
        orderDetail.setCourseName(course.getTitle());
        orderDetail.setCover(course.getCover());
        orderDetail.setOriginAmount(course.getPrice());
        orderDetail.setCouponReduce(new BigDecimal(0));
        orderDetail.setFinalAmount(orderDetail.getOriginAmount().subtract(orderDetail.getCouponReduce()));
        orderDetailService.save(orderDetail);

        //更新优惠券状态
        if(null != orderFormVo.getCouponUseId()) {
            couponInfoFeignClient.updateCouponInfoUseStatus(orderFormVo.getCouponUseId(), orderInfo.getId());
        }

        return orderInfo.getId();
    }

    //订单列表
    @Override
    public Map<String,Object> selectOrderInfdPage(Page<OrderInfo> objectPage, OrderInfoQueryVo orderInfo) {
        Long userId = orderInfo.getUserId();
        Integer orderStatus = orderInfo.getOrderStatus();
        String outTradeNo = orderInfo.getOutTradeNo();
        String phone = orderInfo.getPhone();
        String createTimeBegin = orderInfo.getCreateTimeBegin();
        String createTimeEnd = orderInfo.getCreateTimeEnd();
        QueryWrapper<OrderInfo> wrapper=new QueryWrapper<>();
        //判断条件是否为空
        if(!StringUtils.isEmpty(orderStatus)) {
            wrapper.eq("order_status",orderStatus);
        }
        if(!StringUtils.isEmpty(userId)){
            wrapper.eq("user_id",userId);
        }
        if(!StringUtils.isEmpty(outTradeNo)){
            wrapper.eq("out_trade_no",outTradeNo);
        }
        if(!StringUtils.isEmpty(phone)){
            wrapper.eq("phone",phone);
        }
        if(!StringUtils.isEmpty(createTimeBegin)){
            wrapper.ge("create_time",createTimeBegin);
        }
        if (!StringUtils.hasLength(createTimeEnd)){
            wrapper.le("create_time",createTimeEnd);
        }
        //调用条件分页查询
        Page<OrderInfo> orderInfoPage = baseMapper.selectPage(objectPage, wrapper);
        long total = orderInfoPage.getTotal();
        long pages = orderInfoPage.getPages();
        List<OrderInfo> records = orderInfoPage.getRecords();

        //订单里面包含详情，封装详情数据，根据id查询详情
        records.stream().forEach(a->
                this.getOrderDetail(a));
        Map<String,Object> maps=new HashMap<>();
        maps.put("total",total);
        maps.put("pageCount",pages);
        maps.put("records",records);
        return maps;
    }

    private OrderInfo getOrderDetail(OrderInfo orderInfo) {
        //根据id查询课程名称
        Long id = orderInfo.getId();
        OrderDetail orderDetail = orderDetailService.getById(id);
        if(orderDetail!=null){
            String courseName = orderDetail.getCourseName();
            orderInfo.getParam().put("courseName",courseName);
        }
        return orderInfo;

    }

    @Override
    public void updateOrderStatus(String outTradeNo) {
        LambdaQueryWrapper<OrderInfo> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(OrderInfo::getOutTradeNo,outTradeNo);
            OrderInfo orderInfo = baseMapper.selectOne(wrapper);
            orderInfo.setOrderStatus("1");
            baseMapper.updateById(orderInfo);
        }
    }

